package com.fhao.forum.interceptor;

import com.fhao.forum.config.AppConfig;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${fhao-forum.login.url}")
    private String defaultURL;
    /**
     * 前端处理(对登录请求的预处理)
     * @return true 表示 流程继续. false 表示 流程中断.
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute(AppConfig.USER_SESSION) != null) {
            //用户已经登录
            return true;
        }
        //预防 defaultURL 前头少了 "/",进行校验改正操作
        if(!defaultURL.startsWith("/")) {
            defaultURL = "/"+defaultURL;
        }
        //用户没登录,跳转到登录页面
        response.sendRedirect(defaultURL);
        //中断流程
        return false;
    }
}



















